import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/LoginPage.vue'
import Layout from '@/views/layout/Layout.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/data/manage',
    children: [
      {
        path: '/data/manage',
        name: 'dataManage',
        component: () => import('@/views/DataSource/List.vue')
      },
      {
        path: '/data/collection',
        name: 'dataCollection',
        component: () => import('@/views/DataCollect/List.vue')
      },
      {
        path: '/data/transform',
        name: 'dataTransform',
        component: () => import('@/views/DataTransform/List.vue')
      },
      {
        path: '/data/task',
        name: 'dataTask',
        component: () => import('@/views/DataTask/List.vue')
      },
      {
        path: '/data/log',
        name: 'dataLog',
        component: () => import('@/views/DataLog/List.vue')
      },
      {
        path: '/user/profile',
        name: 'userProfile',
        component: () => import('@/views/user/UserProfile.vue')
      },
      {
        path: '/user/avatar',
        name: 'userAvatar',
        component: () => import('@/views/user/UserAvatar.vue')
      },
      {
        path: '/user/password',
        name: 'userPassword',
        component: () => import('@/views/user/UserPassword.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫，判断用户是否登录
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('token')
  // 判断路由是否需要登录权限
  if (to.path !== '/login') {
    // 需要登录权限
    if (token) {
      // 已登录，允许访问
      next()
    } else {
      // 未登录，跳转到登录页
      next('/login')
    }
  } else {
    // 不需要登录权限的页面
    if (token && to.path === '/login') {
      // 已登录状态下访问登录页，重定向到首页
      next('/data/manage')
    } else {
      // 正常访问
      next()
    }
  }
})

export default router
